package com.bee.app.plugin;

import java.util.List;

import com.bee.app.jfinal.Table;
import com.bee.app.tool.ClassSearcher;
import com.bee.app.util.StringKit;
import com.jfinal.kit.PropKit;
import com.jfinal.log.Logger;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.Model;

/**
 * 自动扫描实体配置映射插件
 * 
 * @author liuzy
 * @version 2015年7月2日
 */
public class LoadModels {

	private Logger log = Logger.getLogger(LoadModels.class);

	private ActiveRecordPlugin arp;

	public LoadModels(ActiveRecordPlugin arp) {
		this.arp = arp;
	}

	public void scan() {
		String path = PropKit.get("model.path");
		if (StringKit.isNullOrEmpty(path)) {
			log.warn("model.path没有设置");
			path = "/";
		}
		List<Class<? extends Model<?>>> classes = ClassSearcher.search(Model.class, path);
		for (Class<? extends Model<?>> clazz : classes) {
			Table table = clazz.getAnnotation(Table.class);
			if (table == null) {
				log.error(clazz.getName() + "没有配置表");
				continue;
			}
			String tableName = table.value();
			if ("".equals(tableName)) {
				log.error(clazz.getName() + "配置表错误");
			} else {
				arp.addMapping(tableName, clazz);
				log.debug("Mapped model:[" + tableName + "] " + clazz.getName());
			}
		}
	}

}
